<template>
<div class="btn-group" ref='dropdownRef'>
    <button @click='handler' class="btn btn-secondary dropdown-toggle" type="button">{{title}}</button>
    <div v-if="Isopen"  class="dropdown-menu dropdown-menu-right" :style="{display: 'block'}" aria-labelledby="dropdownMenuButton">
        <slot></slot>
    </div>
</div>
</template>

<script lang='ts'>
import { defineComponent, onMounted, onUnmounted, ref } from 'vue'
export default defineComponent({
  name: 'Dropdown',
  props: {
    title: {
      type: String,
      require: true
    }
  },
  setup () {
    const Isopen = ref(true)
    const dropdownRef = ref<null| HTMLElement>(null)// 此时用泛型是告诉ts，这个元素类型在完全渲染后其实是一个HTMLElement元素
    const handler = () => {
      Isopen.value = !Isopen.value
    }
    const handle = (e: MouseEvent) => {
      if (dropdownRef.value) {
        if (!dropdownRef.value.contains(e.target as HTMLElement) && Isopen.value === true) {
          Isopen.value = false
        }
      }
    }
    onMounted(() => {
      document.addEventListener('click', handle)
    })
    onUnmounted(() => {
      document.removeEventListener('click', handle)
    })
    return {
      dropdownRef,
      handle,
      Isopen,
      handler
    }
  }
})
</script>

<style>

</style>
